package cn.getech.data.metadata.controller.module;

import cn.getech.data.metadata.entity.CollectionSystemModuleEntity;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 类描述
 * @author: wangzhaowen：kiss
 * @create: 2021/4/19 19:32
 * @version: 2021/4/19
 **/
public class ModuleUtils {

    private static void getParents(Map<Integer, CollectionSystemModuleEntity> moduleMap,
                                   Integer id, List<CollectionSystemModuleEntity> parents) {
        if (moduleMap.get(id) != null) {
            Integer parentId = moduleMap.get(id).getParentId();
            //防止脏数据 出现循环递归 根据实际数据目录不会超过7层   故递归次数不超过20
            if (parentId != null && parentId > 0 && parents.size() < 20) {
                parents.add(moduleMap.get(id));
                getParents(moduleMap, parentId, parents);
            } else {
                parents.add(moduleMap.get(id));
            }
        }
    }

    /**
     * 获取模块的全路径
     *
     * @param list 模块的列表
     * @param id   当前id
     * @return 全路径
     */
    public static String getAllPath(List<CollectionSystemModuleEntity> list, Integer id) {
        List<CollectionSystemModuleEntity> parents = parents(list, id);
        List<String> names = parents.stream().map(CollectionSystemModuleEntity::getSmName).collect(Collectors.toList());
        return String.join("/", names);
    }

    /**
     * 获取根目录
     *
     * @param list 模块的列表
     * @param id   当前id
     * @return 全路径
     */
    public static CollectionSystemModuleEntity getRootParent(List<CollectionSystemModuleEntity> list, Integer id) {
        List<CollectionSystemModuleEntity> parents = parents(list, id);
        if (CollectionUtils.isEmpty(parents)) {
            return null;
        }
        return parents.get(0);
    }

    /**
     * 获取当前目录的所有父目录(包含当前目录)
     *
     * @param list 系统中所有的目录集合
     * @param id   当前目录id
     * @return 父目录集合
     */
    private static List<CollectionSystemModuleEntity> parents(List<CollectionSystemModuleEntity> list, Integer id) {
        Map<Integer, CollectionSystemModuleEntity> moduleMap = new HashMap<>();
        for (CollectionSystemModuleEntity moduleEntity : list) {
            moduleMap.put(moduleEntity.getSmId(), moduleEntity);
        }
        List<CollectionSystemModuleEntity> parents = new ArrayList<>();
        getParents(moduleMap, id, parents);
        parents.sort(Comparator.comparing(CollectionSystemModuleEntity::getSmId));
        return parents;
    }
}
